package com.guat.servlet.picture;

import com.google.gson.Gson;
import com.guat.service.PictureService;
import com.guat.util.FileNameUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

@WebServlet("/addPicture")
//告诉服务器 这个servlet可以用来直接接收文件
@MultipartConfig
public class AddServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //调用获取地址和信息方法
        String[] urlAndInOf = getUrlAndInOf(req);
        String pictureIofo = urlAndInOf[0];
        String pictureName = urlAndInOf[1];
        //截取文件名
        int lastBackslashIndex = pictureName.lastIndexOf("\\");
        if (lastBackslashIndex != -1) {
            String filename = pictureName.substring(lastBackslashIndex + 1);
            System.out.println(filename);
            PictureService pictureService = new PictureService();
            Map<String, Object> pictureMap = pictureService.addPicture(filename, pictureIofo);
            //设置返回前端数据使用UTF-8编码,防止乱码
            resp.setCharacterEncoding("UTF-8");
            //设置响应内容为json,以便前端正确解析返回的数据
            resp.setContentType("application/json");
            //将Map集合转换为json
            Gson gson = new Gson();
            String mapJson = gson.toJson(pictureMap);
            //将数据写入输入流中
            resp.getWriter().write(mapJson);
        } else {
            System.out.println("文件名为空！");
        }
    }

    private static String[] getUrlAndInOf(HttpServletRequest req){
        try {
            String[] str = new String[2];
            List<FileItem> itemList = getItemList(req);
            //遍历集合
            for (FileItem item: itemList) {
                // 判断是否为普通字段
                if (item.isFormField()){
                    //是文字 type="text"
                    //String name = item.getName();
                    String value = item.getString("utf-8");
                    //System.out.println("图片的简介"+value);
                    str[0] = value;
                } else {
                    //是文件 type="file"
                    // 获取上传的文件名,用于截取后缀名,判断文件类型
                    String name = item.getName();
                    //System.out.println("前端上传时的图片文件名"+name);
                    // 截取出后缀名
                    String type = name.substring(name.lastIndexOf("."));
                    // 调用文件名字工具类，传入后缀名，获取路径
                    String path = FileNameUtil.getSaveFilePath(type);
                    //System.out.println("上传的图片文件存储的路径"+path);
                    str[1] = path;
                    //文件字节输入流
                    InputStream inputStream = item.getInputStream();
                    //文件字节输出流
                    FileOutputStream OutputStream = new FileOutputStream(path);
                    //调用java提供的IO工具类复制方法
                    IOUtils.copy(inputStream,OutputStream);
                    //关闭流
                    IOUtils.closeQuietly(inputStream);
                    IOUtils.closeQuietly(OutputStream);
                }
            }
            return str;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    //获取post请求方法体传递的文件和普通字符串,返回值是一个FileItem类型的List集合。
    private static List<FileItem> getItemList(HttpServletRequest req) throws FileUploadException {
        // 创建文件解析工厂对象
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //设置文件缓存目录,如果文件夹不存在则创建一个
        factory.setRepository(FileNameUtil.tmpdir);
        //创建ServletFileUpload对象
        ServletFileUpload fileUpload = new ServletFileUpload(factory);
        //设置字符编码
        fileUpload.setHeaderEncoding("utf-8");
        //解析request，得到上传文件的FileItem对象
        List<FileItem> fileItems = fileUpload.parseRequest(req);
        return fileItems;
    }
}
